<template>
  <div class="container">
    <h3 class="h3">自定义组件（放大、缩小、长度测量、面积测量）</h3>
    <div class="controlbox">
      <div class="getlength0" @click="getlength0('length')" />
      <div class="getarea0" @click="getarea0('area')" />
      <div class="zoomIn" @click="zoomin0()" />
      <div class="zoomOut" @click="zoomout0()" />
    </div>
    <div id="vue-openlayers" />
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
// import OSM from 'ol/source/OSM'
import { XYZ } from 'ol/source'
import MeasureTool from '@/assets/js/measure.js'
import * as control from 'ol/control'
export default {
  data() {
    return {
      map: null
    }
  },
  mounted() {
    this.initMap()
  },

  methods: {
    zoomin0() {
      const czoom = this.map.getView().getZoom()
      this.map.getView().setZoom(czoom + 1)
    },
    zoomout0() {
      const czoom = this.map.getView().getZoom()
      this.map.getView().setZoom(czoom - 1)
    },
    getlength0(x) {
      this.clearMeasure()
      MeasureTool.measure(this.map, x, true)
    },
    getarea0(x) {
      this.clearMeasure()
      MeasureTool.measure(this.map, x, true)
    },
    clearMeasure() { // 清除图层，中间参数为空
      MeasureTool.measure(this.map, '', false)
    },

    initMap() {
      const raster = new Tile({
        source: new XYZ({
          url: 'http://{a-c}.tile.openstreetmap.de/{z}/{x}/{y}.png'
        })
      })
      this.map = new Map({
        target: 'vue-openlayers',
        layers: [raster],
        view: new View({
          center: [-12000000, 4700000],
          zoom: 2
        }),
        controls: control.defaults({
          zoom: false,
          rotate: false,
          attribution: false
        }).extend([])
      })
    }
  }
}
</script>
<style>
.container {
  width: 1240px;
  height: 690px;
  margin: 50px auto;
  border: 1px solid #42b983;
}
#vue-openlayers {
  width: 1200px;
  height: 600px;
  margin: 0 auto;
  border: 1px solid #42b983;
  position: relative;
}
.h3 {
  text-align: center;
}

.controlbox {
    position: absolute;
    z-index: 200;
    bottom: 100px;
    width: 18px;
    padding: 5px 7px;
    height: 120px;
    right: 100px;
    border: 1px solid #ccc;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-content: space-between;
    flex-direction: column;
    background-color: #fff;
}

.getlength0 {
    width: 18px;
    height: 30px;
    background-size: 16px 16px;
}

.getarea0 {
    width: 18px;
    height: 30px;
    background-size: 16px 16px;
}

.zoomIn {
    width: 18px;
    height: 30px;
    background-size: 16px 16px;
}

.zoomOut {
    width: 18px;
    height: 30px;
    background-size: 16px 16px;
}
</style>

